package contract

import (
	"errors"
	"fmt"
	"time"

	"gorm.io/gorm"

	"shop-manager/internal/do"
	"shop-manager/internal/vo"
)

//go:generate newc
type ContractRepo struct {
	db *gorm.DB
}

// CreateContract 创建合同
func (r *ContractRepo) CreateContract(contract *do.Contract) error {
	return r.db.Create(contract).Error
}

// UpdateContract 更新合同
func (r *ContractRepo) UpdateContract(contract *do.Contract) error {
	return r.db.Save(contract).Error
}

// DeleteContract 删除合同
func (r *ContractRepo) DeleteContract(id uint) error {
	return r.db.Delete(&do.Contract{}, id).Error
}

// GetContractByID 根据ID获取合同
func (r *ContractRepo) GetContractByID(id uint) (*do.Contract, error) {
	var contract do.Contract
	err := r.db.First(&contract, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("合同不存在")
		}
		return nil, err
	}

	return &contract, nil
}

// GetContractList 获取合同列表
func (r *ContractRepo) GetContractList(req *vo.ListContractReq) ([]do.Contract, int64, error) {
	var contracts []do.Contract
	var total int64

	// 构建查询
	query := r.db.Model(&do.Contract{})

	// 添加查询条件
	if req.ContractID >0 {
		query = query.Where("id = ?", req.ContractID)
	}
	if req.SupermarketID > 0 {
		query = query.Where("supermarket_id = ?", req.SupermarketID)
	}
	if req.ContractType > 0 {
		query = query.Where("contract_type = ?", req.ContractType)
	}

	if req.IsExpired != -1 {
		isExpired := req.IsExpired
		if isExpired == 0 || isExpired == 1 {
			now := time.Now()
			if isExpired == 0 {
				// 未过期
				query = query.Where("end_time > ?", now)
			} else {
				// 已过期
				query = query.Where("end_time <= ?", now)
			}
		}
	}

	// 获取总数
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	err = query.Offset(offset).Limit(req.PageSize).Order("created_at DESC").Find(&contracts).Error
	if err != nil {
		return nil, 0, err
	}

	// 不需要再手动设置IsExpired，因为它现在是一个方法
	// 超市名称字段已删除，不再需要查询

	return contracts, total, nil
}

// CheckSupermarketExists 检查超市是否存在
func (r *ContractRepo) CheckSupermarketExists(id uint) (bool, error) {
	var count int64
	err := r.db.Table("supermarket").Where("id = ?", id).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}
